<template>
  <div class="header">
    <div>
      <el-main class="main">
        <el-row class="grid-content" :gutter="5" type="flex" justify="start">
          <!-- 显示当前出发地和目的地 -->
          <el-col :span="12">
            <city-searcher v-on:search-city="onSearchCity"></city-searcher>
          </el-col>
          <!-- 选择日期 -->
          <el-col :span="4" :offset="6">          
            <el-date-picker :clearable="false" value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-model="pickedDate"
              type="date" placeholder="选择日期" :picker-options="datePickerOptions"></el-date-picker>
          </el-col>
        </el-row>
        <!-- 日期tab -->
        <div>
          <el-row>
            <el-col :span="2">
              <el-button icon="el-icon-arrow-left" type="primary" @click="lastDateList"></el-button>
            </el-col>
            <el-col :span="20">
              <el-tabs type="card" stretch v-model="pickedDate" style="color:red">
                <el-tab-pane v-for="(item,index) in dateList" :key="index" :label="item" :name="item"></el-tab-pane>
              </el-tabs>
            </el-col>
            <el-col :span="2">
              <el-button icon="el-icon-arrow-right" type="primary" @click="nextDateList"></el-button>
            </el-col>
          </el-row>
        </div>
        <!-- 列表过滤选项 -->
        <div>
          <el-row :gutter="4" type="flex" justify="start">
            <el-col :span="3" v-for="(item,index) in listFilters.filters" :key="index">
              <el-popover placement="bottom">
                <div style="font-weight:bold;font-size:14px;padding:10px 5px 15px 5px">{{item.placeHolder}}</div>
                <el-checkbox-group v-model="item.checked">
                  <el-checkbox v-for="(option,op_index) in item.options" :key="op_index" :label="option">{{option}}
                  </el-checkbox>
                </el-checkbox-group>
                <el-button slot="reference">{{item.placeHolder}} <i class="el-icon-arrow-down"></i></el-button>
              </el-popover>
            </el-col>
          </el-row>
        </div>
        <!-- 航班列表 -->
        <div>
          <el-table empty-text="找不到符合条件的航班" :data="pagedList" border highlight-current-row
            :cell-style="{textAlign: 'center'}" header-cell-class-name="table-head-cell" v-loading="isLoading">
            <el-table-column label="航班号" class-name="flight-airline" prop="flightNames">
            </el-table-column>
            <el-table-column label="航班细节" min-width="180px">
              <template v-slot:default="slotProps">
                <el-badge value="中转" style="margin-top: 10px;margin-right: 40px;" type="primary"
                  :hidden="slotProps.row.tran=='直飞'">

                  <div class="flight-detail">
                    <!-- 起始位置 -->
                    <div class="detail-box">
                      <div class="detail-time">{{formatDateHM(slotProps.row.departTime)}}</div>
                      <div class='detail-airport'>{{slotProps.row.departPort}}</div>
                    </div>
                    <!-- 箭头 -->
                    <div class="detail-arrow">
                      <div>
                        <img src="../assets/flight_information.png" width="75px" height="20px">
                      </div>
                      <div style="color:#999;font-size: 12px;font-weight: 400;">
                        约 {{slotProps.row.totalConsume}} 小时
                      </div>
                    </div>
                    <!-- 到达信息 -->
                    <div class="detail-box">
                      <div class="detail-time">{{formatDateHM(slotProps.row.arriveTime)}}</div>
                      <div class="detail-airport">{{slotProps.row.arrivePort}}</div>
                    </div>
                  </div>
                </el-badge>
              </template>
            </el-table-column>
            <el-table-column label="到达时间">
              <template v-slot:default="slotProps">
                {{formatDateDHM(slotProps.row.arriveTime)}}
              </template>
            </el-table-column>
            <el-table-column label="余票量">
              <template v-slot:default="slotProps">
                <div v-for="(item,index) in slotProps.row.flights" :key="index">
                  <el-badge value="热门" style="margin-top: 10px;margin-right: 20px;" :hidden="item.leftSeat>5">
                    <div style="padding:5px">
                      {{item.flightName}} : {{item.leftSeat}} 张
                    </div>
                  </el-badge>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格">
              <template v-slot:default="slotProps">
                <span class="price">￥{{slotProps.row.totalPrice}}</span>
              </template>
            </el-table-column>
            <el-table-column class="flight-option">
              <template v-slot:default="slotProps">
                <el-tag v-if="stopSelling" type="danger">停 止 网 络 售 票</el-tag>
                <template v-else>
                  <div style="margin: 10px 0" v-if="isRebook">
                    <el-button type="warning " @click="makeOrder(slotProps.row)">改 签</el-button>
                  </div>
                  <div v-else>
                    <div style="margin: 10px 0">
                      <el-button type="warning " @click="makeOrder(slotProps.row)" icon="el-icon-shopping-cart-full">订 购</el-button>
                    </div>
                    <div style="margin: 10px 0">
                      <el-button @click="showDetail(slotProps.row)" icon="el-icon-chat-dot-square">详 情</el-button>
                    </div>
                  </div>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <!-- //底部分页栏 -->
      <div style="display:flex;justify-content:center">
        <div style="background-color:white;padding:0 20px;margin:10px 0">
          <el-pagination background layout="total,prev,pager,next" v-bind:page-count="totalPage"
            v-bind:total="totalAirplanes" v-bind:page-size="pageSize" @current-change="setCurrentPage"></el-pagination>
        </div>
      </div>
      <!-- 航班信息弹窗 -->
      <div>
        <el-dialog title="航班详情" :visible.sync="dialogVisible" center>
          <span>
            <plane-detail v-bind:routeInfo="detailInfo"></plane-detail>
          </span>
          <span slot="footer">
            <el-button type="warning" @click="makeOrder(detailInfo)" icon="el-icon-shopping-cart-full">订 购</el-button>
            <el-button type="info" @click="hideDetail()" icon="el-icon-close">取 消</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script >
import axios from "axios";
import PlaneDetail from "./PlaneDetail.vue";
import CityPicker from "./CityPicker.vue";
import CitySearcher from "./CitySearcher.vue";
export default {
  components: { PlaneDetail, CityPicker, CitySearcher },
  name: "AirplaneList",
  props: {
    isRebook: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      listFilters: {
        filterTran(route) {
          //过滤转乘
          var filter = this.filters.trans_count;
          return filter.checked.length == 0
            ? true
            : filter.checked.indexOf(route.tran) != -1;
        },
        filterAirport(route) {
          //过滤机场
          var filter = this.filters.airport;
          return filter.checked.length == 0
            ? true
            : filter.checked.indexOf(route.departPort) != -1;
        },
        filterDepartTime(route) {
          //过滤起飞时间
          var filter = this.filters.departTime;
          var routeTime = route.departTime.getHours();
          if (filter.checked.length == 0) return true;
          var range = 0;
          if (routeTime < 12 && routeTime >= 6) range = 0;
          else if (routeTime >= 12 && routeTime < 18) range = 1;
          else if (routeTime < 24 && routeTime >= 18) range = 2;
          return filter.checked.indexOf(filter.options[range]) != -1;
        },
        filterArriveTime(route) {
          //过滤到达时间
          var filter = this.filters.arriveTime;
          var routeTime = route.arriveTime.getHours();
          if (filter.checked.length == 0) return true;
          var range = 0;
          if (routeTime < 12 && routeTime >= 6) range = 0;
          else if (routeTime >= 12 && routeTime < 18) range = 1;
          else if (routeTime < 24 && routeTime >= 18) range = 2;
          return filter.checked.indexOf(filter.options[range]) != -1;
        },
        filterFlightName(route) {
          //过滤航班号 or 航班名
          var filter = this.filters.flightName;
          return filter.checked.length == 0
            ? true
            : filter.checked.indexOf(route.flightNames) != -1;
        },
        filters: {
          trans_count: {
            placeHolder: "中转/直飞",
            options: ["中转", "直飞"],
            checked: [],
            value: ""
          },
          flightName: {
            placeHolder: "航班号",
            options: [],
            checked: [],
            value: ""
          },
          airport: {
            placeHolder: "机场",
            options: [],
            checked: [],
            value: ""
          },
          departTime: {
            placeHolder: "出发时间",
            options: ["上午 6~12点", "下午 12~18点", "晚上 18~24点"],
            checked: [],
            value: ""
          },
          arriveTime: {
            placeHolder: "到达时间",
            options: ["上午 6~12点", "下午 12~18点", "晚上 18~24点"],
            checked: [],
            value: ""
          }
        }
      },
      datePickerOptions: {
        disabledDate: function(time) {
          var today = new Date();
          var future = new Date();
          future.setTime(future.getTime() + 3600 * 1000 * 24 * 30);
          today.setTime(today.getTime() - 3600 * 1000 * 24);
          return (
            time.getTime() < today.getTime() ||
            time.getTime() > future.getTime()
          );
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      headDate: Number,
      pickedDate: "",
      rawList: [],
      isLoading: false,
      stopSelling: false,
      currentPage: 1,
      pageSize: 6,
      dialogVisible: false,
      detailInfo: null,
      routes: {
        departCity: "",
        arriveCity: ""
      },
      processRawData: {
        getAirport: function(filter, airport) {
          if (filter.options.indexOf(airport) == -1)
            filter.options.push(airport);
        },
        getFlightName: function(filter, name) {
          if (filter.options.indexOf(name) == -1) filter.options.push(name);
        }
      }
    };
  },
  methods: {
    getData() {
      // 根据当前时间查询数据
      axios
        .post(this.$GLOBAL.localHost + "search/", {
          startPos: this.routes.departCity,
          endPos: this.routes.arriveCity,
          startTime: this.pickedDate
        })
        // .get("/route.json")
        .then(response => {
          console.log(response);
          this.isLoading = true;
          this.rawList = [];
          for (let item of response.data.root) {
            for (let flight of item) {
              flight.consume = Math.round(
                (new Date(flight.endTime) - new Date(flight.startTime)) /
                  (60 * 60 * 1000)
              );
            }
          }
          // 处理数据
          for (let item of response.data.root) {
            //改签机票的时候不展示转乘
            if (this.isRebook && item.length > 1) continue;
            // 路线对象
            var route = {
              totalPrice: 0,
              totalConsume: 0,
              tran: "",
              departPort: String,
              arrivePort: String,
              departTime: Date,
              arriveTime: Date,
              flights: Array,
              departCity: "北京",
              arriveCity: "吉隆坡",
              flightNames: ""
            };
            var last = item[0];
            var first = item[item.length - 1];
            //城市处理
            route.departCity = first.start;
            route.arriveCity = last.end;
            //机场处理
            route.departPort = first.startAir;
            route.arrivePort = last.endAir;
            route.tran = item.length > 1 ? "中转" : "直飞";
            //存入过滤器
            this.processRawData.getAirport(
              this.listFilters.filters.airport,
              first.startAir
            );
            this.processRawData.getFlightName(
              this.listFilters.filters.flightName,
              first.flightName
            );
            // 计算总价格和时间
            for (let flight of item) {
              route.totalPrice += parseInt(flight.price);
              route.totalConsume += flight.consume;
              route.flightNames = route.flightNames + flight.flightName;
              if (item.indexOf(flight) != item.length - 1)
                route.flightNames = route.flightNames + "  ";
            }
            route.departTime = new Date(first.startTime);
            route.arriveTime = new Date(last.endTime);
            //保存所有机票
            route.flights = item.sort(function(a, b) {
              return a.order - b.order;
            });
            // 加入数组
            this.rawList.push(route);
          }
          this.isLoading = false;
        })
        .catch(error => console.log(error));
    },
    setCurrentPage(currentPage) {
      // 修改当前数据页码
      this.currentPage = currentPage;
    },
    showDetail(route) {
      // 显示航班详情
      this.detailInfo = route;
      this.dialogVisible = true;
    },
    hideDetail() {
      // 隐藏详情页
      this.dialogVisible = false;
    },
    makeOrder(info) {
      // 用户点击订购时 发出信号
      this.hideDetail();
      this.$GLOBAL.is_booking = true
      this.$emit("make-order", info);
    },
    getNowTime() {
      this.$set(this, "headDate", new Date().getTime());
      this.$set(this, "pickedDate", this.toDateString(new Date(this.headDate)));
    },
    toDateString(date) {
      var yyyy = date.getFullYear();
      var MM = date.getMonth() + 1;
      if (MM < 10) MM = "0" + MM;
      var DD = date.getDate();
      if (DD < 10) DD = "0" + DD;
      return yyyy + "-" + MM + "-" + DD;
    },
    formatDateHM(date) {
      // 获取小时和分钟
      const hour = date.getHours();
      const min = date.getMinutes();
      var h = hour >= 10 ? hour : "0" + hour;
      var m = min >= 10 ? min : "0" + min;
      return h + ":" + m;
    },
    formatDateDHM(date) {
      // 获取日期 时间
      var MM = date.getMonth() + 1;
      if (MM < 10) MM = "0" + MM;
      var DD = date.getDate();
      if (DD < 10) DD = "0" + DD;
      const hour = date.getHours();
      var h = hour > 10 ? hour : "0" + hour;
      const min = date.getMinutes();
      var m = min > 10 ? min : "0" + min;
      return MM + "-" + DD + " " + h + ":" + m;
    },
    onSearchCity(val) {
      this.routes.departCity = val.start_city;
      this.routes.arriveCity = val.arrive_city;
      if (this.routes.arriveCity == "" || this.routes.departCity == "") {
        this.$message({
          message: "请选择出发地/目的地",
          type: "warning"
        });
      } else if (this.pickedDate == "") {
        this.$message({
          message: "请选择日期",
          type: "warning"
        });
      } else this.getData();
    },
    findDate(val) {
      return val === this.pickedDate;
    },
    lastDateList() {
      const date = new Date();
      this.headDate =
        this.headDate - 60 * 60 * 24 * 5 * 1000 < date.getTime()
          ? date.getTime()
          : this.headDate - 60 * 60 * 24 * 5 * 1000;
    },
    nextDateList() {
      this.headDate += 60 * 60 * 24 * 5 * 1000;
    }
  },
  computed: {
    filtedList: function() {
      var filted = [];
      for (let route of this.rawList) {
        if (
          this.listFilters.filterDepartTime(route) &&
          this.listFilters.filterTran(route) &&
          this.listFilters.filterAirport(route) &&
          this.listFilters.filterFlightName(route) &&
          this.listFilters.filterArriveTime(route)
        )
          filted.push(route);
      }
      return filted;
    },
    //分页数据
    pagedList: function() {
      //todo:加入过滤器
      var start = (this.currentPage - 1) * this.pageSize;
      var end = start + this.pageSize;
      end = end < this.filtedList.length ? end : this.filtedList.length;
      return this.filtedList.slice(start, end);
    },
    // 总页数
    totalPage: function() {
      return this.rawList.length / this.pageSize;
    },
    // 总航班数
    totalAirplanes: function() {
      return this.rawList.length;
    },
    // 时间列表
    dateList: function() {
      var dateList = new Array();
      for (var x = 0; x < 5; x++) {
        var ctime = this.headDate + 60 * 60 * 24 * x * 1000;
        var date = this.toDateString(new Date(ctime));
        dateList.push(date);
      }
      return dateList;
    }
  },
  watch: {
    // 用户修改当前日期时 重新询问数据
    pickedDate(val, oldVal) {
      var pick = new Date(val);
      var now = new Date();
      if (
        pick.getFullYear() == now.getFullYear() &&
        pick.getMonth() == now.getMonth() &&
        pick.getDate() == now.getDate()
      ) {
        this.stopSelling = true;
      } else {
        this.stopSelling = false;
      }
      if (this.dateList.findIndex(this.findDate) == -1)
        this.headDate = new Date(this.pickedDate).getTime();

      this.getData(val);
    }
  },
  created() {
    this.getNowTime();
  }
};
</script>
<style>
.header {
  font-weight: bolder;
  font-size: x-large;
  /* background-color: rgb(233, 238, 243); */
  background-image: url(../assets/airplane-background.jpg);
  background-size: cover; /* 使图片平铺满整个浏览器（从宽和高的最大需求方面来满足，会使某些部分无法显示在区域中） */
  background-repeat: no-repeat;
  padding: 20px;
}
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
  height: 100%;
}
.flight-airline {
  font-size: 16px;
  color: #555;
}
.flight-detail {
  display: flex;
  justify-content: center;
  align-content: space-around;
  text-align: center;
  color: black;
  padding: 5px;
}
.detail-box {
  padding: 0 5px;
}
.detail-airport {
  margin: 10px 0;
  font-size: small;
}
.detail-time {
  width: 100px;
  font-size: 30px;
  font-weight: normal;
}
.detail-arrow {
  font-size: 20px;
}
.price {
  font-size: 30px;
  color: #ff8205;
}
.main {
  width: 80%;
  height: 960px;
  margin: 0 auto;
  background-color: rgb(253, 253, 253);
}
/* table */
.table-head-cell {
  background-color: #409eff !important;
  color: #fff;
  font-weight: 500;
}
</style>